package com.group2.operations.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.OSSObject;
import com.group2.operations.common.api.ApiResult;
import com.group2.operations.config.AliyunConfig;
import com.group2.operations.mapper.ContractMapper;
import com.group2.operations.mapper.FlowMapper;
import com.group2.operations.mapper.UserMapper;
import com.group2.operations.model.Contract;
import com.group2.operations.service.ContractService;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ContractServiceImpl implements ContractService{
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private OSS ossClient;
    @Autowired
    private AliyunConfig aliyunConfig;
    @Autowired
    private TaskService taskService;
    @Autowired
    private FlowMapper flowMapper;
    @Autowired
    private UserMapper userMapper;


    /**
     * 列举某个用户的所有合同
     * @param uid 用户ID
     * @return
     */
    @Override
    public List<Contract> listContracts(int uid) {
        return contractMapper.queryContractByUid(uid);
    }

    /**
     * 根据合同ID查找合同文件名
     * @param id
     * @return
     */
    @Override
    public String queryContractNameById(int id) {
        return contractMapper.queryContractNameById(id);
    }

    /**
     * 下载OSS文件
     * @param os 输出流
     * @param objectName 文件名
     * @throws IOException
     */
    @Override
    public void exportOssFile(OutputStream os, String objectName) throws IOException {
        OSSObject ossObject = ossClient.getObject(aliyunConfig.getBucketName(), objectName);
        //读取文件内容
        BufferedInputStream in = new BufferedInputStream(ossObject.getObjectContent());
        BufferedOutputStream out = new BufferedOutputStream(os);
        byte[] buffer = new byte[1024];
        int length = 0;
        while((length = in.read(buffer)) != -1) {
            out.write(buffer, 0, length);
        }
        if(out != null) {
            out.flush();
            out.close();
        }
        if(in != null) {
            in.close();
        }
    }

    /**
     * 对合同进行操作
     * @param username 用户名
     * @param cid 合同ID
     * @param action 动作（签署或拒绝）
     */
    @Override
    @Transactional
    public ApiResult actContract(String username, int cid, String action) {
        // 获取正在进行的合同签署任务
        Task task = taskService.createTaskQuery().taskAssignee(username).singleResult();
        //获取流程ID
        Map<String, Object> map = taskService.getVariables(task.getId());
        String processId = (String) map.get("processId");

        //通过或驳回
        Map<String, Object> variables = new HashMap<>();
        variables.put("signOutcome", action);
        taskService.complete(task.getId(), variables);

        //数据库状态更新
        String state = action.equals("通过") ? "合同签署" : "合同驳回";
        flowMapper.updateSignProcessState(processId, state, new Date());

        //将合同改为已签订状态
        contractMapper.signContract(cid);

        //改变角色为代理商并修改签订时间
        if(action.equals("通过")) {
            userMapper.changeRoleToAgent(username);
            contractMapper.updateTime(cid, new Date());
        }

        return ApiResult.success("合同处理成功");
    }
}
